<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="收费项名称" prop="chargeItemsName">
          <el-input
            v-model="queryParams.chargeItemsName"
            placeholder="请输入收费项名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="收费类型" prop="chargeItemsType">
          <el-select
            v-model="queryParams.chargeItemsType"
            placeholder="请选择收费类型"
            clearable
            size="small"
          >
            <el-option label="按次" :value="1"/>
            <el-option label="按天" :value="2"/>
            <el-option label="按个" :value="6"/>
            <el-option label="按里程" :value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item label="收费绑定项" prop="bindingCharges">
          <el-select
            v-model="queryParams.bindingCharges"
            placeholder="请选择收费绑定项"
            clearable
            size="small"
          >
            <el-option label="新增订单" :value="1"/>
            <el-option label="还车验车" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可选" prop="isOptional">
          <el-select
            v-model.number="queryParams.isOptional"
            placeholder="请输入是否可选"
            clearable
            size="small"
          >
            <el-option label="是" :value="1"/>
            <el-option label="否" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isAvailable">
          <el-select v-model.number="queryParams.isAvailable">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="未启用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索
          </el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
          </el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="custom_card">
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            class="first-plain-btn"
            size="medium"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['plan:items:add']"
          >新增
          </el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="itemsList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column
          label="收费项名称"
          align="center"
          prop="chargeItemsName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="收费项说明"
          align="center"
          prop="remark"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="收费绑定项"
          align="center"
          prop="bindingCharges"
          min-width="120"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{
                scope.row.bindingCharges == 1 ? '新增订单' : '还车验车'
              }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="收费类型"
          align="center"
          min-width="80"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            <dict-tag
              :options="dict.type.charge_type"
              :value="row.chargeItemsType"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价(元)" align="center" prop="unitPrice">
          <template slot-scope="scope">
            <span>{{ scope.row.unitPrice||'--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收费次数上限" align="center" min-width="120" prop="upperLimitOfNumber">
          <template slot-scope="scope">
            <span v-if="scope.row.bindingCharges == 2">--</span>
            <span v-else>{{ scope.row.upperLimitOfNumber && scope.row.upperLimitOfNumber >= 0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收费金额上限" align="center" min-width="120" prop="upperLimitOfAmount">
          <template slot-scope="scope">
            <span v-if="scope.row.bindingCharges == 2">--</span>
            <span v-else>{{ scope.row.upperLimitOfAmount && scope.row.upperLimitOfAmount >= 0 ? scope.row.upperLimitOfAmount : '无上限' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="是否可选"
          align="center"
          min-width="80"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-if="scope.row.bindingCharges == 2">--</span>
            <span v-else>{{ scope.row.isOptional | isOptional }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="租户"
          align="center"
          prop="tenantName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="是否启用"
          align="center"
          min-width="80"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_available"
              :value="scope.row.isAvailable"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
          fixed="left"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['plan:items:edit']"
            >修改
            </el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['plan:items:remove']"
            >删除
            </el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 1)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['store:store:edit']"
            >启用
            </el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 0)"
              v-if="scope.row.isAvailable == 1"
              v-hasPermi="['store:store:edit']"
            >停用
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改收费项对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="收费项名称" prop="chargeItemsName">
          <el-input
            v-model="form.chargeItemsName"
            placeholder="请输入收费项名称"
            clearable
            style="width: 100%"
            maxlength="20" show-word-limit
          />
        </el-form-item>

        <el-form-item label="收费绑定项" prop="bindingCharges" required>
          <el-radio :label="1" v-model.number="form.bindingCharges" @change="form.chargeItemsType=1">新增订单</el-radio>
          <el-radio :label="2" v-model.number="form.bindingCharges" @change="form.chargeItemsType=1">还车验车</el-radio>
        </el-form-item>

        <el-form-item label="收费类型" prop="chargeItemsType">
          <template v-for="dict in dict.type.charge_type">
            <el-radio :label="parseInt(dict.value)"  @change="changeType" v-if="form.bindingCharges==2||dict.value!=3" v-model.number="form.chargeItemsType">{{dict.label}}</el-radio>
          </template>
        </el-form-item>

        <template v-if="form.bindingCharges==1">
          <el-form-item label="是否可选" prop="isOptional" required>
            <el-radio :label="1" v-model.number="form.isOptional" @change="changeType">是</el-radio>
            <el-radio :label="2" v-model.number="form.isOptional" @change="changeType">否</el-radio>
          </el-form-item>

          <el-form-item label="单价" prop="unitPrice">
            <el-input
              v-model="form.unitPrice"
              placeholder="请输入单价"
              clearable
              style="width: 100%"
              @keyup.native="form.unitPrice = oninput(form.unitPrice,2)||0.01"
              @blur="form.unitPrice = form.unitPrice>=0.01?form.unitPrice:0.01"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="收费次数上限" prop="upperLimitOfNumber" class="is-required" v-if="showUpperLimit">
            <el-input
              v-model="form.upperLimitOfNumber"
              :disabled="numberChecked"
              placeholder="请输入"
              clearable
              @keyup.native="form.unitPrice = oninput(form.unitPrice,0)"
              style="width:50%">
            </el-input>
            <span style="margin-right: 25px"><dict-tag style="display: inline-block" :options="dict.type.charge_type" :value="form.chargeItemsType"/></span>
            <el-checkbox v-model="numberChecked">无上限</el-checkbox>
          </el-form-item>
          <el-form-item label="收费金额上限" prop="upperLimitOfAmount" class="is-required" v-if="showUpperLimit">
            <el-input
              v-model="form.upperLimitOfAmount"
              :disabled="amountChecked"
              placeholder="请输入"
              @keyup.native="form.unitPrice = oninput(form.unitPrice,0)"
              clearable
              style="width:50%">
            </el-input>
            <span style="margin-right: 25px">元</span>
            <el-checkbox v-model="amountChecked">无上限</el-checkbox>
          </el-form-item>
        </template>
        <el-form-item label="是否启用" prop="isAvailable" required>
          <el-radio :label="1" v-model.number="form.isAvailable">启用</el-radio>
          <el-radio :label="0" v-model.number="form.isAvailable">停用</el-radio>
        </el-form-item>

        <el-form-item label="收费项说明" prop="remark">
          <el-input
            maxlength="500" show-word-limit
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listItems,
  getItems,
  delItems,
  addItems,
  updateItems,
  exportItems,
  stopUsingEnabled,
} from '@/api/plan/items'

export default {
  name: 'Items',
  dicts: [
    'charge_type',
    'store_type',
    'sys_available',
    'store_class',
    'service_mode',
  ],
  data() {
    var validatePass = (rule, value, callback) => {
      if (!this.numberChecked) {
        if (!value) {
          callback(new Error('请输入次数上限'));
        } else if (Number(value) <= 0) {
          callback(new Error('请输入大于0的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (!this.amountChecked) {
        if (!value) {
          callback(new Error('请输入金额上限'));
        } else if (Number(value) <= 0) {
          callback(new Error('请输入大于0的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收费项表格数据
      itemsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chargeItemsName: null,
        chargeItemsType: null,
        bindingCharges: null,
        isOptional: null,
        isAvailable: null,
        deptId: null,
        tenantId: null,
      },
      numberChecked: false,
      amountChecked: false,
      showUpperLimit: true,
      // 表单参数
      form: {
        isOptional: 1,
        isAvailable: 1,
        bindingCharges: 1,
        chargeItemsType: 1,
        unitPrice: null,
        upperLimitOfNumber: null,
        upperLimitOfAmount: null,
      },
      // 表单校验
      rules: {
        chargeItemsName: [
          {required: true, message: '请输入收费项名称', trigger: 'blur'},
        ],
        bindingCharges: [
          {required: true, message: '请选择收费绑定项', trigger: 'change'},
        ],
        chargeItemsType: [
          {required: true, message: '请选择收费类型', trigger: 'change'},
        ],
        unitPrice: [
          {required: true, message: '请输入单价', trigger: 'change'},
        ],
        upperLimitOfNumber: [
          {validator: validatePass, trigger: 'change'},
        ],
        upperLimitOfAmount: [
          {validator: validatePass2, trigger: 'change'}
        ],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询收费项列表 */
    getList() {
      this.loading = true
      this.queryParams.projectType = 1
      listItems(this.queryParams).then((response) => {
        this.itemsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        chargeItemsId: null,
        chargeItemsName: null,
        chargeItemsType: 1,
        bindingCharges: 1,
        isOptional: 1,
        isAvailable: 1,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: null,
        tenantId: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.chargeItemsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.changeType()
      this.open = true
      this.title = '添加收费项'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const chargeItemsId = row.chargeItemsId || this.ids
      getItems(chargeItemsId).then((response) => {
        this.form = response.data

        if ((this.form.chargeItemsType === 1 || this.form.chargeItemsType === 6) && this.form.isOptional === 2) {
          this.showUpperLimit = false;
        } else {
          this.showUpperLimit = true;
        }

        if (this.form.upperLimitOfNumber >= 0) {
          this.numberChecked = false
        } else {
          this.form.upperLimitOfNumber = null
          this.numberChecked = true
        }
        if (this.form.upperLimitOfAmount >= 0) {
          this.amountChecked = false
        } else {
          this.form.upperLimitOfAmount = null
          this.amountChecked = true
        }



        this.open = true
        this.title = '修改收费项'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let formData = {
            ...this.form
          }
          if (this.numberChecked) {
            formData.upperLimitOfNumber = -1
          }
          if (this.amountChecked) {
            formData.upperLimitOfAmount = -1
          }
          if (!this.showUpperLimit) {
            formData.upperLimitOfNumber = -1
            formData.upperLimitOfAmount = -1
          }

          formData.projectType = 1
          if (this.form.chargeItemsId != null) {
            updateItems(formData).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addItems(formData).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    changeType() {
      if ((this.form.chargeItemsType == 1 || this.form.chargeItemsType == 6) && this.form.isOptional == 2) {
        this.numberChecked = true;
        this.amountChecked = true;
        this.showUpperLimit = false;
      } else {
        this.numberChecked = false;
        this.amountChecked = false;
        this.showUpperLimit = true;
      }
    },
    /** 启用/停用 */
    handleAvailable(row, available) {
      stopUsingEnabled({
        chargeItemsId: row.chargeItemsId,
        isAvailable: available,
      }).then((response) => {
        this.$modal.msgSuccess('修改成功')
        this.open = false
        this.getList()
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chargeItemsIds = row.chargeItemsId || this.ids
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(function () {
          return delItems(chargeItemsIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal
        .confirm('是否确认导出所有收费项数据项？')
        .then(() => {
          this.exportLoading = true
          return exportItems(queryParams)
        })
        .then((response) => {
          this.$download.name(response.msg)
          this.exportLoading = false
        })
        .catch(() => {
        })
    },
  },
}
</script>
